package com.dkm.modules.wx.cashrecord.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dkm.commons.BaseController;
import com.dkm.commons.Response;
import com.dkm.config.wx.WxPayProperties;
import com.dkm.modules.sys.user.model.User;
import com.dkm.modules.sys.user.service.UserService;
import com.dkm.modules.wx.cashrecord.model.OperatorBalance;
import com.dkm.modules.wx.cashrecord.model.OperatorCashRecord;
import com.dkm.modules.wx.cashrecord.service.OperatorBalanceService;
import com.dkm.util.redis.RedisUtils;
import com.github.binarywang.wxpay.bean.entpay.EntPayRequest;
import com.github.binarywang.wxpay.bean.entpay.EntPayResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.dkm.modules.wx.cashrecord.service.OperatorCashRecordService;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.dkm.util.HttpContext.getIp;

/**
 * @ClassName OperatorCashRecordController
 * @Description: 代理商端 提现控制器
 * @Author yangbin
 * @Date 2019-09-22 09:46
 * @Version V1.0
 **/
@Api(tags = {"9 代理商端--我的"})
@RestController
@RequestMapping("/my")
public class MyController extends BaseController{

    private final static Logger logger = LoggerFactory.getLogger(MyController.class);
    @Autowired
    private OperatorCashRecordService operatorCashRecordService;
    @Autowired
    private UserService userService;
    @Autowired
    private OperatorBalanceService operatorBalanceService;

    @Autowired
    private WxPayProperties wxPayProperties;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private RedisUtils redisUtils;

    /*短信过期时间 单位：秒*/
    private static long SMS_EXPIRE = 60*5;



    @ApiOperation("提现记录")
    @GetMapping("/getCashRecord")
    @ApiImplicitParam(paramType = "header",name = "token",value = "身份认证Token")
    public Response getCashRecord(@ApiParam("页数") @RequestParam("pageNo")int pageNo,
                                  @ApiParam("每页显示数") @RequestParam("pageSize")int pageSize){

        Page<Map<String,Object>> page = new Page<>(pageNo,pageSize);
        /*组装查询参数*/
        Map<String, Object> params = new HashMap<>();
        /*代理商*/
        params.put("userId",getUserId());
        /*查询分页提现记录*/
        IPage<Map<String,Object>> cashRecords = operatorCashRecordService.getCashRecords(page,params);
        return Response.ok(cashRecords);
    }

    @GetMapping("/getMyData")
    @ApiOperation(value = "我的钱包 余额")
    @ApiImplicitParam(paramType = "header",name = "token",value = "身份认证Token")
    public Response<OperatorBalance> getMyBalance(){
        OperatorBalance operatorBalance = operatorBalanceService.getBalanceByUserId(getUserId());
        return Response.ok(operatorBalance);
    }

    @ApiOperation("绑定微信")
    @GetMapping("/bindWx")
    @ApiImplicitParam(paramType = "header",name = "token",value = "身份认证Token")
    public Response bindWx(@ApiParam("微信获取openId使用的code")@RequestParam("code") String code){
        return userService.bindWx(getUserNm(),code);
    }

    @ApiOperation("提现")
    @GetMapping("/cashWithdrawal")
    @ApiImplicitParam(paramType = "header",name = "token",value = "身份认证Token")
    public Response cashWithdrawal(@ApiParam("提现金额")@RequestParam("amount") Float amount,
                                   @ApiParam("短信验证码")@RequestParam("code") String code){
        /*先验证手机验证码*/
        String userId = getUserNm();
        User user = userService.getUserById(userId);
        String openid = user.getWeixinOpenid();
        //如果用户没有openId  提示用户未进行绑定
        if(openid==null){
            return Response.error(-1,"账户未绑定微信");
        }
        String vailCode = redisUtils.get(user.getMobile());
        if(!code.equals(vailCode)){
            return Response.error(-2,"短信验证码有误");
        }


        ///获取余额
        OperatorBalance operatorBalance = operatorBalanceService.getBalanceByUserId(getUserId());
        Float account = operatorBalance.getAmount();
        //判断申请提现金额是否大于账户余额
        if(amount>account) {
            return Response.error(-3, "非法操作：申请提现金额大于可提现金额");
        }

        EntPayRequest entPayRequest = new EntPayRequest();
        entPayRequest.setAppid(wxPayProperties.getAppId());
        entPayRequest.setMchId(wxPayProperties.getMchId());
        //生成订单号
        String orderId = UUID.randomUUID().toString().replaceAll("-", "");
        entPayRequest.setPartnerTradeNo(orderId);
        entPayRequest.setOpenid(user.getWeixinOpenid());
        entPayRequest.setCheckName("NO_CHECK");
        entPayRequest.setAmount((int) (amount * 100));
        entPayRequest.setDescription("充电桩平台提现");
        entPayRequest.setSpbillCreateIp(getIp());
        EntPayResult entPayResult = null;
        /*提现记录*/
        OperatorCashRecord operatorCashRecord = new OperatorCashRecord();
        try {
            entPayResult = wxPayService.getEntPayService().entPay(entPayRequest);
            //更新余额
            operatorBalance.setAmount(operatorBalance.getAmount()-amount);
            operatorBalanceService.updateBlance(operatorBalance);
            /*设置提现状态为成功*/
            operatorCashRecord.setStatus(0);
            logger.info("entPayResult : " + entPayResult);
        } catch (WxPayException e) {
            /*设置提现状态为失败*/
            operatorCashRecord.setStatus(1);
            logger.error("付款失败，返回报文" + e);
            String errorReason = e.getReturnMsg() + ":" + e.getErrCodeDes();
            operatorCashRecord.setErrorReason(errorReason);
            return Response.error(errorReason);
        }finally {
            operatorCashRecord.setOperaterId(user.getId());
            operatorCashRecord.setAmount(amount);
            operatorCashRecord.setCreateTime(new Date());
            operatorCashRecord.setOrderNumber(orderId);
            /*插入提现记录*/
            operatorCashRecordService.addCashRecord(operatorCashRecord);
        }

        return Response.ok();

    }

    @ApiOperation("发送短信验证码")
    @GetMapping("/sendMsg")
    @ApiImplicitParam(paramType = "header",name = "token",value = "身份认证Token")
    public Response sendMsg(@ApiParam("手机号")@RequestParam("mobile")String mobile){
        logger.info("发送短信验证码");

        User user = userService.getUserById(getUserNm());
        String openid = user.getWeixinOpenid();
        //如果用户没有openId  提示用户未进行绑定
        if(openid==null){
            return Response.error(-1,"账户未绑定微信");
        }
        if(user.getMobile()==null){
            return Response.error(-3,"账户未绑定手机号");
        }
        if(!mobile.equals(user.getMobile())){
            return Response.error(-2,"输入的手机与绑定手机号不一致");
        }
        String redisCode = redisUtils.get(mobile);
        if(redisCode!=null){
            return Response.error(-1,"请勿重复发送");
        }

        String code = RandomStringUtils.randomNumeric(6);
        redisUtils.delete(mobile);
        redisUtils.set(mobile,code,SMS_EXPIRE);
        operatorBalanceService.sendSms(mobile,code);
        return Response.ok(0,"验证码发送成功");
    }



}
